package ink.metoo.gude.module.file.config

import ink.metoo.gude.properties.CloudflareProperties
import ink.metoo.gude.module.file.service.FileService
import ink.metoo.gude.module.file.service.impl.NoneFileServiceImpl
import ink.metoo.gude.module.file.service.impl.R2FileServiceImpl
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import software.amazon.awssdk.services.s3.S3Client

@Configuration
class S3Config(
    private val cloudflareProperties: CloudflareProperties
) {

    @Bean
    @ConditionalOnProperty(name = ["gude.cloudflare.r2.enable"], havingValue = "true")
    fun r2S3Client(): S3Client = CloudflareR2Client.buildS3Client(
        cloudflareProperties.authId,
        cloudflareProperties.r2.accessKeyId,
        cloudflareProperties.r2.secretAccessKey
    )

    @Bean
    @ConditionalOnBean(S3Client::class)
    fun r2FileServiceImpl(
        s3Client: S3Client,
    ): FileService = R2FileServiceImpl(cloudflareProperties, s3Client)

    @Bean
    @ConditionalOnMissingBean
    fun noneFileServiceImpl(): FileService = NoneFileServiceImpl()

}
